package com.scrx.ymg.action;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.scrx.ymg.entity.AgentDrawings;
import com.scrx.ymg.entity.OrderForm;
import com.scrx.ymg.entity.User;
import com.scrx.ymg.service.head.IHeadService;
import com.scrx.ymg.service.orderform.IOrderFormService;
import com.scrx.ymg.service.supermarket.ISuperMarketService;
import com.scrx.ymg.service.user.IUserService;
import com.scrx.ymg.util.PayConfigUtil;
import com.scrx.ymg.utilqy.CollectionUtil;
import com.scrx.ymg.utilqy.HttpUtils;
import com.scrx.ymg.utilqy.JsonResult;
import com.scrx.ymg.utilqy.PayUtil;
import com.scrx.ymg.utilqy.ResponseData;
import com.scrx.ymg.utilqy.SerializerFeatureUtil;
import com.scrx.ymg.utilqy.WebUtil;
import com.scrx.ymg.utilqy.XmlUtil;

@Controller
@RequestMapping("/refundAction")
public class RefundAction {
	
	private static final Logger LOG = Logger.getLogger(TransferController.class);

    private static final String TRANSFERS_PAY = "https://api.mch.weixin.qq.com/secapi/pay/refund"; // 退款

    private static final String APP_ID = PayConfigUtil.APPID;

    private static final String MCH_ID = PayConfigUtil.MCH_ID;

    //private static final String API_SECRET =PayConfigUtil.APP_SECRET;
    
    private static final String TGRefund_URL =PayConfigUtil.TGRefund_URL;
    
    @Autowired
	private IUserService users;
    
    @Autowired
	private IOrderFormService  ofs;

    /**
     * 微信支付退款
     * @param TransferNo
     * @param request
     * @param response
     */
	@ResponseBody
	@RequestMapping(value = "/transferPay", produces = "text/json;charset=UTF-8")
    public void transferPay(String TransferNo,HttpServletRequest request, HttpServletResponse response) {
        LOG.info("退款单号:"+TransferNo);
        //判断订单是否能够退款
        Map<String, String> restmap = null;
        OrderForm order=null;
        try {
        	 order = ofs.getOrderFormByOrderId(TransferNo);
        	 if(order.getTypeId()==3&&order.getParent()!=null&&order.getParent()>0){
        		 OrderForm sub = ofs.getOrderFormById(order.getParent());
        	 }
        	//User user = users.findById(order.getUserId());
            Double total_fee = order.getTotalMoney()*100;
            Map<String, String> parm = new HashMap<String, String>();
            parm.put("appid", APP_ID); //公众账号appid
            parm.put("mch_id", MCH_ID); //商户号
            parm.put("op_user_id",MCH_ID); 
            parm.put("nonce_str", PayUtil.getNonceStr()); //随机字符串
            if(order.getTypeId()==3&&order.getParent()!=null&&order.getParent()>0){
       		 OrderForm sub = ofs.getOrderFormById(order.getParent());
       		Double total_fee2 = sub.getTotalMoney()*100;
       		parm.put("out_trade_no",sub.getOrderFormId().toString()); //商户订单号
       		parm.put("total_fee", total_fee2.intValue()+""); //订单金额
       	    }else{
       	    parm.put("out_trade_no",order.getOrderFormId().toString()); //商户订单号
       	    parm.put("total_fee", total_fee.intValue()+""); //订单金额
       	    }
            parm.put("out_refund_no",order.getOrderFormId().toString()); //商户退货订单号
            parm.put("refund_fee", total_fee.intValue()+""); //退款金额
            parm.put("sign", PayUtil.getSign(parm, PayConfigUtil.API_KEY));
			String restxml = HttpUtils.posts(TRANSFERS_PAY, XmlUtil.xmlFormat(parm, false));
			restmap = XmlUtil.xmlParse(restxml);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        if (CollectionUtil.isNotEmpty(restmap) && "SUCCESS".equals(restmap.get("result_code"))) {
            LOG.info("退款成功：" + restmap.get("err_code") + ":" + restmap.get("err_code_des"));
            Map<String, String> transferMap = new HashMap<>();
            transferMap.put("partner_trade_no", restmap.get("partner_trade_no"));//商户转账订单号
            transferMap.put("payment_no", restmap.get("payment_no")); //微信订单号
            transferMap.put("payment_time", restmap.get("payment_time")); //微信支付成功时间

            String msg = ofs.returnOrderForm(order);
            LOG.info("退款成功-订单状态修改:"+msg);
            if(msg.equals("true")){
            	WebUtil.response(response,
                        WebUtil.packJsonp(TGRefund_URL,
                                JSON.toJSONString(new JsonResult(1, "退款成功", new ResponseData(null, transferMap)),
                                        SerializerFeatureUtil.FEATURES)));
            }else{
            	WebUtil.response(response,
                        WebUtil.packJsonp(TGRefund_URL,
                                JSON.toJSONString(new JsonResult(1, "退款成功!订单出错", new ResponseData(null, transferMap)),
                                        SerializerFeatureUtil.FEATURES)));
            }
        }else {
            if (CollectionUtil.isNotEmpty(restmap)) {
                LOG.info("退款失败：" + restmap.get("err_code") + ":" + restmap.get("err_code_des"));
            }
            WebUtil.response(response, WebUtil.packJsonp(TGRefund_URL, JSON
                    .toJSONString(new JsonResult(-1, "退款失败", new ResponseData()), SerializerFeatureUtil.FEATURES)));
        }

    }


}
